#include "multi_layout_widget.h"

#include <QList>

class MultiLayoutWidgetPrivate {
public:
    QWidget *mainWidget;
    QList<QWidget*> widgetList;
};

MultiLayoutWidget::MultiLayoutWidget(QWidget *parent)
    : QFrame{parent}
{
    d = std::make_unique<MultiLayoutWidgetPrivate>();
    d->mainWidget = new QWidget(this);
    d->mainWidget->raise();
}

void MultiLayoutWidget::setLayout(QLayout *layout)
{
    d->mainWidget->setLayout(layout);
}

void MultiLayoutWidget::addWidget(QWidget *widget)
{
    if(!widget) return;
    widget->setParent(this);
    d->widgetList.append(widget);
    widget->setGeometry(this->contentsRect());
    widget->raise();
}

void MultiLayoutWidget::insertWidget(int index, QWidget *widget)
{
    if(!widget) return;
    if(index > d->widgetList.size())
        index = d->widgetList.size();
    widget->setParent(this);
    d->widgetList.insert(index, widget);
    widget->setGeometry(this->contentsRect());
    widget->raise();

    for(int i = index + 1; i < d->widgetList.size(); ++i) {
        d->widgetList[i]->raise();
    }
}

QWidget *MultiLayoutWidget::widget(int index)
{
    if(index > d->widgetList.size())
        return nullptr;
    return d->widgetList[index];
}

void MultiLayoutWidget::removeWidget(QWidget *widget)
{
    if(d->widgetList.removeOne(widget)) {
        widget->deleteLater();
    }
}

void MultiLayoutWidget::removeWidget(int index)
{
    if(index < d->widgetList.size()) {
        QWidget *widget = d->widgetList[index];
        d->widgetList.removeAt(index);
        widget->deleteLater();
    }
}

void MultiLayoutWidget::widgetSetMouseEvent(QWidget *, bool state)
{

}

void MultiLayoutWidget::widgetSetMouseEvent(int index, bool state)
{

}

bool MultiLayoutWidget::event(QEvent *e)
{
    switch (e->type()) {
    case QEvent::Resize:
        d->mainWidget->setGeometry(this->contentsRect());
        foreach (QWidget *widget, d->widgetList) {
            widget->setGeometry((this->contentsRect()));
        }
        break;
    default:
        break;
    }

    return QWidget::event(e);
}
